package com.farm.wcp.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

import com.farm.wcp.client.utils.HttpUtils;
import com.farm.wcp.client.utils.WdasJsonMap;

/**
 * 接口模型實現類
 * 
 * @author macpl
 *
 */
public class WcpClient {
	private Map<String, String> urls;
	private String secret;
	private String operatorLoginname;
	private String operatorPassword;
	private String baseUrl;

	private String guestUrl;
	public WcpClient(String baseUrl, String secret, String operatorLoginname, String operatorPassword) {
		super();
		this.secret = secret;
		this.baseUrl = baseUrl;
		this.operatorLoginname = operatorLoginname;
		this.operatorPassword = operatorPassword;
	}

	/**
	 * 校驗接口執行情況
	 * 
	 * @param url
	 * 
	 * @param json
	 */
	public static void validateBackJson(String url, JSONObject json) {
		String state = json.get("STATE").toString();
		if (state.equals("1")) {
			throw new RuntimeException(json.get("MESSAGE").toString() + " by " + url);
		}
	}

	/**
	 * 填充密钥和接口用户信息
	 * 
	 * @param para
	 */
	private void initBaseParas(Map<String, String> para) {
		para.put("operatorLoginname", operatorLoginname);
		para.put("operatorPassword", operatorPassword);
		para.put("secret", secret);
	}

	private Map<String, String> getApiUrls() {
		urls = new HashMap<>();
		urls.put("getOrg", baseUrl + "/get/organization.do");
		urls.put("editOrg", baseUrl + "/put/organization.do");
		urls.put("addOrg", baseUrl + "/post/organization.do");
		urls.put("delOrg", baseUrl + "/delete/organization.do");
		urls.put("getUser", baseUrl + "/get/user.do");
		urls.put("editUser", baseUrl + "/put/user.do");
		urls.put("delUser", baseUrl + "/delete/user.do");
		urls.put("addUser", baseUrl + "/post/user.do");
		urls.put("getCertificate", baseUrl + "/regist/login.do");
		urls.put("getPara", baseUrl + "/get/parameter.do");
		urls.put("pubPara", baseUrl + "/put/parameter.do");

		urls.put("getPost", baseUrl + "/get/posts.do");
		urls.put("postPost", baseUrl + "/post/post.do");
		urls.put("putPost", baseUrl + "/put/post.do");
		urls.put("deletePost", baseUrl + "/delete/post.do");
		urls.put("bindPost", baseUrl + "/bind/posts.do");
		
		urls.put("cachingHtml", baseUrl + "/caching/html.do");
		return urls;
	}

	/**
	 * 创建一个组织机构
	 * 
	 * @param org
	 */
	public void creatRemoteOrg(String appid, int sort, String name, String parentappid) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("appid", appid);
		para.put("sort", new Integer(sort).toString());
		para.put("name", name);
		if (parentappid != null && !parentappid.toUpperCase().equals("NONE")) {
			para.put("parentid", getRemoteOrgByAppid(parentappid).getString("ID"));
		}
		JSONObject editOrgJson = HttpUtils.httpPost(getApiUrls().get("addOrg"), para);
		validateBackJson(getApiUrls().get("addOrg"), editOrgJson);
	}

	public void editRemoteOrg(String appid, int sort, String name, String parentid) {
		if (name.equals("广州佳众联科技有限公司-T3221")) {
			System.out.print("12");
		}
		WdasJsonMap remoteOrg = getRemoteOrgByAppid(appid);
		WdasJsonMap remoteParentOrg = null;
		String remoteParentId = null;
		if (remoteOrg.getString("PARENTID").equals("NONE")) {
			remoteParentId = "NONE";
		} else {
			remoteParentOrg = getRemoteOrg(remoteOrg.getString("PARENTID"));
			remoteParentId = remoteParentOrg.getString("APPID");
		}
		if (remoteOrg.getInt("SORT") != sort || !remoteOrg.getString("NAME").equals(name)
				|| !remoteParentId.equals(parentid)) {
			// 有变化就更新
			Map<String, String> editpara = new HashMap<String, String>();
			initBaseParas(editpara);
			editpara.put("id", remoteOrg.getString("ID"));
			editpara.put("sort", new Integer(sort).toString());
			editpara.put("name", name);
			if (StringUtils.isNotBlank(parentid)) {
				if (parentid.equals("NONE")) {
					editpara.put("parentid", "NONE");
				} else {
					WdasJsonMap porg = getRemoteOrgByAppid(parentid);
					if (remoteParentOrg != null) {
						editpara.put("parentid", porg.getString("ID"));
					}
				}
			}
			JSONObject editOrgJson = HttpUtils.httpPost(getApiUrls().get("editOrg"), editpara);
			validateBackJson(getApiUrls().get("editOrg"), editOrgJson);
		}
	}

	/**
	 * 获得远程机构
	 * 
	 * @param localOrgid
	 * @return
	 */
	public WdasJsonMap getRemoteOrgByAppid(String appid) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("appid", appid);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("getOrg"), para);
		validateBackJson(getApiUrls().get("getOrg"), json);
		WdasJsonMap wjm = new WdasJsonMap(json.toMap());
		if (wjm.getInt("DATA", "totalsize") > 0) {
			List<WdasJsonMap> wjms = wjm.getList("DATA", "list");
			if (wjms.size() > 0) {
				WdasJsonMap remoteOrg = wjms.get(0);
				return remoteOrg;
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	/**
	 * 获得远程机构
	 * 
	 * @param localOrgid
	 * @return
	 */
	public WdasJsonMap getRemoteOrg(String remoteOrgId) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("id", remoteOrgId);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("getOrg"), para);
		validateBackJson(getApiUrls().get("getOrg"), json);
		WdasJsonMap wjm = new WdasJsonMap(json.toMap());
		if (wjm.getInt("DATA", "totalsize") > 0) {
			List<WdasJsonMap> wjms = wjm.getList("DATA", "list");
			if (wjms.size() > 0) {
				WdasJsonMap remoteOrg = wjms.get(0);
				return remoteOrg;
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	public void delRemoteOrg(String remoteOrgId) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("id", remoteOrgId);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("delOrg"), para);
		validateBackJson(getApiUrls().get("delOrg"), json);
	}

	public WdasJsonMap getRemoteUser(String loginname) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("loginname", loginname);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("getUser"), para);
		validateBackJson(getApiUrls().get("getUser"), json);
		WdasJsonMap wjm = new WdasJsonMap(json.toMap());
		if (wjm.getInt("DATA", "totalsize") > 0) {
			List<WdasJsonMap> wjms = wjm.getList("DATA", "list");
			WdasJsonMap remoteuser = wjms.get(0);
			return remoteuser;
		} else {
			return null;
		}
	}

	public WdasJsonMap getRemoteUserByRemotId(String remotuserid) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("id", remotuserid);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("getUser"), para);
		validateBackJson(getApiUrls().get("getUser"), json);
		WdasJsonMap wjm = new WdasJsonMap(json.toMap());
		if (wjm.getInt("DATA", "totalsize") > 0) {
			List<WdasJsonMap> wjms = wjm.getList("DATA", "list");
			WdasJsonMap remoteuser = wjms.get(0);
			return remoteuser;
		} else {
			return null;
		}
	}

	public void editRemoteUser(String remoteUserid, String name, String state, String type, String loacalOrgid) {
		Map<String, String> editpara = new HashMap<String, String>();
		initBaseParas(editpara);
		editpara.put("id", remoteUserid);
		if (StringUtils.isNotBlank(loacalOrgid)) {
			WdasJsonMap remoteOrg = getRemoteOrgByAppid(loacalOrgid);
			String remoteOrgId = remoteOrg == null ? null : remoteOrg.getString("ID");
			if (StringUtils.isNotBlank(remoteOrgId)) {
				editpara.put("orgid", remoteOrgId);
			}
		}
		editpara.put("name", name);
		if (StringUtils.isNotBlank(state)) {
			editpara.put("state", state);
		}
		if (StringUtils.isNotBlank(type)) {
			editpara.put("type", type);
		}
		JSONObject editUserJson = HttpUtils.httpPost(getApiUrls().get("editUser"), editpara);
		validateBackJson(getApiUrls().get("editUser"), editUserJson);
	}

	public void creatRemoteUser(String loginname, String name, String userstate, String usertype, String loacalOrgid,
			String node) {
		Map<String, String> editpara = new HashMap<String, String>();
		initBaseParas(editpara);
		editpara.put("name", name);
		editpara.put("loginname", loginname);
		if (StringUtils.isNotBlank(loacalOrgid)) {
			WdasJsonMap remoteOrg = getRemoteOrgByAppid(loacalOrgid);
			if (remoteOrg != null) {
				String remoteOrgId = remoteOrg.getString("ID");
				if (StringUtils.isNotBlank(remoteOrgId)) {
					editpara.put("orgid", remoteOrgId);
				}
			}
		}
		if (node != null) {
			editpara.put("comments", node);
		}
		editpara.put("state", userstate);
		editpara.put("type", usertype);
		JSONObject creatUserJson = HttpUtils.httpPost(getApiUrls().get("addUser"), editpara);
		validateBackJson(getApiUrls().get("addUser"), creatUserJson);
	}

	public void creatRemoteUser(String loginname, String name, String userstate, String usertype, String loacalOrgid) {
		creatRemoteUser(loginname, name, userstate, usertype, loacalOrgid, null);
	}

	public void delRemoteUser(String remoteUserid) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("id", remoteUserid);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("delUser"), para);
		validateBackJson(getApiUrls().get("delUser"), json);
	}

	/**
	 * 获得免密登录key
	 * 
	 * @param loginname
	 * @return
	 */
	public String getCertificate(String loginname) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("loginname", loginname);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("getCertificate"), para);
		validateBackJson(getApiUrls().get("getCertificate"), json);
		WdasJsonMap wjm = new WdasJsonMap(json.toMap());
		return wjm.getString("CERTIFICATE");
	}

	public boolean isLive(boolean isThrowError) {
		try {
			@SuppressWarnings("unused")
			WdasJsonMap wjm = getRemoteOrgByAppid("NONE");
			return true;
		} catch (Exception e) {
			if (isThrowError) {
				throw e;
			} else {
				return false;
			}
		}
	}

	public void putRemotePara(String key, String val) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("key", key);
		para.put("val", val);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("pubPara"), para);
		validateBackJson(getApiUrls().get("pubPara"), json);
	}

	public String getRemotePara(String key) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("key", key);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("getPara"), para);
		validateBackJson(getApiUrls().get("getPara"), json);
		WdasJsonMap wjm = new WdasJsonMap(json.toMap());
		return wjm.getString("DATA");
	}

	public WdasJsonMap getRemoteOrgs(Integer page) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		if (page != null) {
			para.put("page", page.toString());
		}
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("getOrg"), para);
		validateBackJson(getApiUrls().get("getOrg"), json);
		WdasJsonMap wjm = new WdasJsonMap(json.toMap());
		return wjm;
	}

	public WdasJsonMap getRemoteUsers(Integer page) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		if (page != null) {
			para.put("page", page.toString());
		}
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("getUser"), para);
		validateBackJson(getApiUrls().get("getUser"), json);
		WdasJsonMap wjm = new WdasJsonMap(json.toMap());
		return wjm;
	}

	public String getSecret() {
		return secret;
	}

	public String getOperatorLoginname() {
		return operatorLoginname;
	}

	public String getOperatorPassword() {
		return operatorPassword;
	}

	public String getBaseUrl() {
		return baseUrl;
	}

	/**
	 * 查询远程岗位
	 * 
	 * @param sourceflag 来源前缀，将匹配以sourceflag开头的sourceid
	 * @return
	 */
	public List<WdasJsonMap> getRemotePosts(String sourceflag) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("sourceflag", sourceflag);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("getPost"), para);
		validateBackJson(getApiUrls().get("getPost"), json);
		WdasJsonMap wjm = new WdasJsonMap(json.toMap());
		if (wjm.getList("DATA").size() > 0) {
			List<WdasJsonMap> wjms = wjm.getList("DATA");
			return wjms;
		} else {
			return null;
		}
	}

	/**
	 * 查询远程岗位
	 * 
	 * @param sourceid 来源id
	 * @return
	 */
	public WdasJsonMap getRemotePost(String sourceid) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("sourceflag", sourceid);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("getPost"), para);
		validateBackJson(getApiUrls().get("getPost"), json);
		WdasJsonMap wjm = new WdasJsonMap(json.toMap());
		if (wjm.getList("DATA").size() > 0) {
			List<WdasJsonMap> wjms = wjm.getList("DATA");
			return wjms.get(0);
		} else {
			return null;
		}
	}

//	urls.put("postPost", baseUrl + "/post/post.do");

	/**
	 * 创建远程岗位角色
	 * 
	 * @param sourceid 来源id,一般为来源系统的flag+来源系统id
	 * @param orgappid 组织机构的appid(可空)
	 * @param name     岗位名称
	 * @param extendis 作用范围1:含子机构,0：仅仅当前机构,2：所有机构
	 * @return
	 */
	public void creatRemotePost(String sourceid, String orgappid, String name, String extendis) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		if (StringUtils.isNotBlank(sourceid)) {
			para.put("sourceid", sourceid);
		} else {
			throw new RuntimeException("sourceid is null");
		}
		if (StringUtils.isNotBlank(orgappid)) {
			para.put("orgappid", orgappid);
		}
		if (StringUtils.isNotBlank(name)) {
			para.put("name", name);
		} else {
			throw new RuntimeException("name is null");
		}
		if (StringUtils.isNotBlank(extendis)) {
			para.put("extendis", extendis);
		} else {
			throw new RuntimeException("extendis is null");
		}
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("postPost"), para);
		validateBackJson(getApiUrls().get("postPost"), json);
	}

	/**
	 * 修改更新岗位
	 * 
	 * @param sourceid 来源id 必填
	 * @param name     可空
	 * @param extendis 可空 作用范围1:含子机构,0：仅仅当前机构,2：所有机构
	 */
	public void editRemotePost(String sourceid, String name, String extendis) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		if (StringUtils.isNotBlank(sourceid)) {
			para.put("sourceid", sourceid);
		} else {
			throw new RuntimeException("sourceid is null");
		}
		if (StringUtils.isNotBlank(name)) {
			para.put("name", name);
		}
		if (StringUtils.isNotBlank(extendis)) {
			para.put("extendis", extendis);
		}
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("putPost"), para);
		validateBackJson(getApiUrls().get("putPost"), json);
	}

	/**
	 * 删除远程岗位
	 * 
	 * @param sourceid 来源id 必填
	 */
	public void delRemotePost(String sourceid) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		if (StringUtils.isNotBlank(sourceid)) {
			para.put("sourceid", sourceid);
		} else {
			throw new RuntimeException("sourceid is null");
		}
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("deletePost"), para);
		validateBackJson(getApiUrls().get("deletePost"), json);
	}

	/**
	 * 绑定人员到岗位
	 * 
	 * @param sourceids  可以为空，为空时清楚用户的所有岗位（匹配来源前缀）
	 * @param sourceflag 来源前缀，将匹配以sourceflag开头的sourceid，在绑定前会删除匹配该来源的全部人员岗位
	 * @param loginname  绑定到的用户登录名
	 */
	public void bindRemotePost(String sourceidOrPostId, String sourceflag, String loginname) {
		List<String> ids = new ArrayList<String>();
		ids.add(sourceidOrPostId);
		bindRemotePost(ids, sourceflag, loginname);
	}

	/**
	 * 绑定人员到岗位
	 * 
	 * @param sourceids  可以为空，为空时清楚用户的所有岗位（匹配来源前缀）
	 * @param sourceflag 来源前缀，将匹配以sourceflag开头的sourceid，在绑定前会删除匹配该来源的全部人员岗位
	 * @param loginname  绑定到的用户登录名
	 */
	public void bindRemotePost(List<String> sourceidsOrPostIds, String sourceflag, String loginname) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		if (sourceidsOrPostIds != null) {
			String ids = null;
			for (String id : sourceidsOrPostIds) {
				if (ids == null) {
					ids = id;
				} else {
					ids = ids + "," + id;
				}
			}
			para.put("sourceids", ids);
		}
		if (StringUtils.isNotBlank(sourceflag)) {
			para.put("sourceflag", sourceflag);
		} else {
			sourceflag = null;
		}
		if (StringUtils.isNotBlank(loginname)) {
			para.put("loginname", loginname);
		} else {
			throw new RuntimeException("loginname is null");
		}
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("bindPost"), para);
		validateBackJson(getApiUrls().get("bindPost"), json);
	}

	/**
	 * 清空用户岗位
	 * 
	 * @param loginname
	 */
	public void clearAllPost(String loginname) {
		bindRemotePost(new ArrayList<String>(), null, loginname);
	}

	/**
	 * 在服务器缓存html内容并返回缓存key
	 * 
	 * @param html
	 * @return
	 */
	public String cachingHtml(String html) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		if (StringUtils.isNotBlank(html)) {
			para.put("html",html);
		} else {
			throw new RuntimeException("html is null");
		}
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("cachingHtml"), para);
		validateBackJson(getApiUrls().get("cachingHtml"), json);
		return json.getString("KEY");
	}

	/**
	 * 设置客户端访问wcp的url地址，在某些返回wcp url的方法中会用到
	 * 
	 * @param url
	 */
	public void setGuestUrl(String url) {
		guestUrl = url;
	}

	/**
	 * 返回url，在浏览器中打开私有知识的创建界面
	 * 
	 * @param html
	 * @return
	 */
	public String getCreatPrivateTextUrl(String html,String loginname) {
		String contentkey = cachingHtml(html);
		String loginkey=getCertificate(loginname);
		return guestUrl+"webprivate/home.do?contentkey="+contentkey+"&LOGIN_CERTIFICATE="+loginkey;
	}

}
